<?php

namespace app\admin\controller;

use think\Controller;
use think\Request;
use think\Db;
//分页功能
use think\Paginator;
use think\Validate;
use think\Paginator\driver\Bootstrap;

class Classdate extends AdminController
{
    //展示页面
    public  function index()
    {   
      //页面分页
        $classdate = db('classdate');
        $list = $classdate
              ->order('id desc')
              ->paginate(5, false,['query'=>request()->param()])
              ->each(function($item, $key){
        $item['starttime'] = date('Y-m-d H:i:s', $item['starttime']);
       
        return $item;
    });
        $page = $list->render();
        $this->assign('list', $list);
        $this->assign('page', $page);
        

         
       $data = Db::field('c.id,c.coid,c.starttime,c.classname,c.longtime,co.coursename,c.state ')
                 ->name('classdate')
                 ->alias('c')
                 ->join('course co','c.coid = co.id')
                 ->order('id desc')
                 ->paginate(5);
        // echo Db::getLastSql();
             
        // var_dump($data);die;
        
          $a = [];
        foreach ($data as $v) {
            $b=date('Y-m-d',$v['starttime']);
            $c = array_push($v,$b);
            $d = $v['coursename'];
            $e = array_push($v,$d);
            $a[] = $v;
        }

        // var_dump($a);die;
         $t=Db::field('coursename')
             ->name('course')
             ->where('display',1)
             ->select();
        // var_dump($t);die;
        $e=[];
       foreach ($t as $key => $j) {
         foreach ($j as $k => $s) {
           $e[] = $s;
         }
       }
       
        // var_dump($e);
        // var_dump($a);die;

        return View('',[
            'data'=>$a,
            'e' =>$e,
            'page'=>$page,
            'list'=>$list
             ]);
    }
 
  

    //执行搜索功能,执行分页功能
    public function  select(Request $request)
    {   

       //接收数据
       $p = $request->post();
       $data = [
        'coursename' => $p['coursename'],
        'classname' => $p['classname'],
       ];

        //判断让用户先选课程
        if($data['coursename']==='option1'){
          return $this->error('请先选择所属的课程',url('admin/classdate/index'));
        }


      $res = Db::field('coursename,id')
               ->name('course')
               ->where('coursename',$data['coursename'])
               ->find();

       //判断是否选择了班期
        if($data['classname']===''){
                // var_dump($res);die;
      $b =Db::field('classname,coid,starttime,longtime,id,state')
            ->name('classdate')
            ->where('coid',$res['id'])
            ->select();
     

    }else{
          $b =Db::field('classname,coid,starttime,longtime,id,state')
            ->name('classdate')
            ->where('coid',$res['id'])
            ->where('classname',$data['classname'])
            ->select();

      }

      if(empty($b)){
         return $this->error('你填写的班期不存在,请重新输入');
         }

          $a = [];
        foreach ($b as $v) {
            $c=date('Y-m-d',$v['starttime']);
            $d = array_push($v,$c);
            $g= $res['coursename'];
            $f = array_push($v,$g);
            $a[] = $v;
        }


       $t=Db::field('coursename')
             ->name('course')
             ->select();
        // var_dump($t);die;
        $e=[];
       foreach ($t as $key => $j) {
         foreach ($j as $k => $s) {
           $e[] = $s;
         }
       }
       
        //页面分页
        $classdate = db('classdate');
        $list = $classdate->order('id asc')
                           ->where('coid',$res['id'])
                           ->where('classname',$data['classname'])
                          ->paginate(5, false,['query'=>request()->param()])
                          ->each(function($item, $key){
        $item['starttime'] = date('Y-m-d H:i:s', $item['starttime']);
        
        return $item;
    });
        $page = $list->render();
        $this->assign('list', $list);
        $this->assign('page', $page);

      return view('classdate/index',[
            'data'=>$a,
            'e' =>$e,
            'list'=>$list,
            'page'=>$page
             ]);

    }



    //执行新增
    public function add()
    {    
          $t=Db::field('coursename')
             ->name('course')
             ->select();
        $e=[];
       foreach ($t as $key => $j) {
         foreach ($j as $k => $s) {
           $e[] = $s;
         }
       }
       
        return View('',[
            'e' =>$e
             ]);
    }
    //提交新增数据
     public function save(Request $request)
    {
    
      $p = $request->post();
      // var_dump($p);die;
      
      $a=[ 'coursename' =>$p['coursename']];
           //判断coursename不能为空
           if($p['coursename']==='option1'){
            return $this->error('添加的课程名不能为空');
           }
    //执行新增前的判断
       //验证
       
       $rule =[
                'classname' => 'require|max:20|chsDash',
                 'longtime' => 'require|number',
              ];
              $msg =[
                'classname.require'=>'班期不能为空',
                'classname.max'=> '班期长度有点长',
                'classname.chsDash'=>'班期名称只能是汉字、字母、数字和下划线_及破折号-',
                 'longtime.require'=>'班期时长不能为空',
                 'longtime.number'=>'班期时长只能为时间'
              ];
              $data = [
              'classname' => strtolower($p['classname']),
              
              'longtime' => $p['longtime'],
              'state'=>$p['state'],
             ];
             // var_dump($data);die;
             $res = Db::name('course')
                       ->where('coursename',$a['coursename'])
                       ->find();
              $data['coid']=$res['id'];
              $data['starttime']=time();


              $validate = new Validate($rule, $msg);
            if (!$validate->check($data)) {
            $this->error($validate->getError());
            }
                  // var_dump($data);die;

     //2.判断新增的班期以前是否存在
        $a = Db::field('classname')
               ->name('classdate')
               ->select();
          $b=[];
        foreach ($a as $k => $v) {
          $b[]=$v['classname'];
        }      
        // var_dump($b);die;
         if(in_array($data['classname'],$b)){
            return  $this->error('不能添加同名的班期,请重新添加');
        }
        
       
       $result = Db::name('classdate')
               ->data($data)
               ->insert();
     //执行添加
    if($result > 0){
        return $this ->success('添加成功',url('admin/classdate/index'));
      }else{
        return $this->error('添加失败,请重试');
      }

    }

     //编辑课程(edit)
    public function edit($id)
    {
        //查数据
        $data = Db::name('classdate')
                  ->where('id ='.$id)
                  ->find();
        
      $data['starttime']=date('Y-m-d',$data['starttime']);
      // var_dump($data);die;
        $res  = Db::field('coursename')
              ->name('course')
              ->where('id ='.$data['coid'])
              ->find();
          // var_dump($res);die;
       return view('',[
         'data'=>$data,
         'res'=>$res
          ]);
    }

     //更新编辑的班期的信息
     public  function update(Request $request, $id)
    {

      $p = $request->post();
      // var_dump($p);die;
       
        //验证
      $rule =[
                'classname' => 'require|max:20|chsDash',
                 'longtime' => 'require|number',
              ];
              $msg =[
                'classname.require'=>'班期不能为空',
                'classname.max'=> '班期长度有点长',
                'classname.chsDash'=>'班期名称只能是汉字、字母、数字和下划线_及破折号-',
                 'longtime.require'=>'班期时长不能为空',
                 'longtime.number'=>'班期时长只能为数字'
              ];
            $a =['coursename' => $p['coursename']];
        // var_dump($tt);die;
        $data =[
        'classname' =>strtolower($p['classname']),
        'longtime' => $p['longtime'],
        'starttime'=>strtotime($p['starttime']),
        'state'=>$p['state']
        ];
         $b = Db::field('id')
                ->name('course')
                ->where(['coursename'=>$a['coursename']])
                ->find();
         $c = Db::field('coid')
                 ->name('classdate')
                 ->where(['coid'=>$b['id']])
                 ->find();
          // var_dump($b);die;
         $data['coid']=$c['coid'];
      $validate = new Validate($rule,$msg);
      if(!$validate->check($data)){
      $this->error($validate->getError());
      }
         // var_dump($data);die;
        $res = Db::name('classdate')
                    ->where(['id'=> $id])
                    ->update($data);
         // var_dump($res);die;
        if($res > 0){
           $this->success('编辑成功',url('admin/classdate/index'));
        }else{
       $this->error('编辑失败,请重试');
    } 
}
      
     public function delete($id)
     {

        $res = Db::name('classdate')
                 ->where(['id'=>input('id')])
                 ->delete();
        // var_dump($res);die;
        if($res){
            $arr['status'] =1;
            $arr['msg'] = '删除成功';
            return $arr;
        }else{
            $arr['status'] = 2;
            $arr['msg'] = '删除失败';
            return $arr;  
        }
}
}